package com.nenglai.admin.modular.report.service;

import com.nenglai.admin.modular.report.service.output.Output;
import com.nenglai.admin.modular.report.service.upload.Upload;
import com.nenglai.common.response.ErrorCode;
import com.nenglai.common.response.ResponseException;
import com.nenglai.common.util.FileUtil;
import com.nenglai.common.util.SpringUtil;
import com.nenglai.model.report.entity.Download;
import com.nenglai.model.report.entity.Template;
import com.nenglai.model.report.service.IDownloadService;
import com.nenglai.model.report.service.ITemplateService;
import com.nenglai.report.Params;
import com.nenglai.report.enums.ReportEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 报表服务
 *
 * @author kongdehui
 * @date 2021/06/21 13:10
 **/
@Slf4j
@Service
public class ReportService {

    @Resource
    ITemplateService templateService;

    @Resource
    IDownloadService downloadService;

    /**
     * 报表导出
     *
     * @param tplId  模板Id
     * @param params 导出数据
     */
    public Object output(Long tplId, Params params) throws Exception {

        log.info("模板={}, data={}，导出报表！", tplId, params);
        Template template = templateService.getById(tplId);
        if (template == null) {
            log.info("模板={}不存在！", tplId);
            throw new ResponseException(ErrorCode.REPORT_TEMPLATE_NOT_EXIST);
        }

        // 下载模板文件流
        Upload upload = SpringUtil.getBean(template.getService(), Upload.class);
        File templateFile = upload.download(template);

        // 获取模板处理对象
        Output output = SpringUtil.getBean(params.getService(), Output.class);
        return output.output(template, templateFile, params);
    }

    /**
     * @param reportId reportId
     * @param response response
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public void download(String reportId, HttpServletResponse response)
            throws IOException, ClassNotFoundException {

        log.info("报告={}，下载报表！", reportId);
        Download download = downloadService.getById(reportId);
        if (download == null) {
            log.info("报告={}不存在！", reportId);
            throw new ResponseException(ErrorCode.REPORT_NOT_EXIST);
        }

        if (!ReportEnum.REPORT_SHARED.getValue().equals(download.getShared().toString())) {
            throw new ResponseException(ErrorCode.NO_SHARED_REPORT_NOT_SUPPORTED_DOWNLOAD);
        }

        Output output = SpringUtil.getBean(download.getService(), Output.class);
        File file = output.download(download);

        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1000];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        fis.close();

        String suffix = FileUtil.suffix(download.getDownload());
        byte[] bytes = bos.toByteArray();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(download.getName(), "UTF-8") + "." + suffix);
        response.setContentLength(bytes.length);
        response.getOutputStream().write(bytes);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

}
